/**
 * @Description:
 * @Author: jiaxiuc
 * @Date: 2024-04-16
 * @LastEditors: jiaxiuc
 * @LastEditTime: 2024-04-18
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// import { clientService } from '@/api'
import storage from '@/utils/storage'
import CONFIG from '@/config/config'
//import { tools } from '@/utils/tools'
import routers from './route'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: routers,
})

// const whiteList = ['login', 'bindFeiShu','error404',] // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title || to.meta.pageTitle || CONFIG.SITENAME
  const noPermission = to.meta?.noPermission || false //是否跳过
  if (noPermission) {
    return next()
  }
  // TOKEN
  let token = storage.getItem(CONFIG.TOKEN)
  //let token = tools.getCookie(CONFIG.COOKIE_NAME)
  // 如果有code
  if (token) {
    if (store.getters.roles.length === 0) {
      // 判断当前用户是否已拉取完user_info信息
      // 拉取user_info
      store
        .dispatch('GetUserInfo')
        .then((res) => {
          const roles = res.role
          // console.log(roles)
          store.dispatch('GenerateRoutes', roles).then(() => {
            // 生成可访问的路由表
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            return next({ ...to }) // hack方法 确保addRoutes已完成
          })
        })
        .catch((er) => {
          console.log(96, 'router', er)
          store.dispatch('Logout')
          // console.log(err)
          return next(
            next({
              name: 'Login',
              query: {
                ...to.query,
              },
            }),
          )
        })
    } else {
      console.log(104, 'router')
      next()
    }
  } else {
    if (to.name === 'Auth' || to.name === 'Login') {
      next()
    } else {
      next({
        name: 'Auth',
        query: {
          ...to.query,
          // 通过 url 传递查询字符串参数
          diy_redirect: to.fullPath, // 把登录成功需要返回的页面告诉登录页面
        },
      })
    }
  }
})

export default router
